package pers.qianyu.month_202011.date_20201122;

/**
 * 探讨问题：求二叉树的节点数
 * 222. 完全二叉树的节点个数
 * https://leetcode-cn.com/problems/count-complete-tree-nodes/
 *
 * @author mizzle rain
 * @date 2020-11-22 22:17
 */
public class CountBinaryTree {
    /**
     * 普通二叉树的深度
     */
    public int countTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return 1 + countTree(root.left) + countTree(root.right);
    }

    /**
     * 满二叉树
     */
    public int countTree2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        TreeNode node = root;
        int height = 0;
        // 计算二叉树的深度
        while (node != null) {
            height++;
            node = node.right;
        }
        return (int) (Math.pow(2, height) - 1);
    }

    /**
     * 完全二叉树
     */
    public int countTree3(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int lheight = 0, rheight = 0;
        TreeNode node = root.left;
        while (node != null) {
            lheight++;
            node = node.left;
        }
        node = root.right;
        while (node != null) {
            rheight++;
            node = node.right;
        }
        if (lheight == rheight) {
            return (int) (Math.pow(2, lheight) - 1);
        }
        return 1 + countTree3(root.left) + countTree3(root.right);
    }

    /**
     * 二叉树定义
     */
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
